#include "login.h"
#include "ui_login.h"
#include <QApplication>
#include <QDebug>
#include <QMessageBox>
#include <QSqlQuery>
#include <QFile>
#include <QCheckBox>
#include <QMouseEvent>
#include "custom_warning.h"
#include "book.h"
#include "admin.h"
#include <QFormLayout>
#include <QDialog>
#include<QTextEdit>
#include <QImage>
#include <QPainter>
#include <QRandomGenerator>
#include <QLabel>
Login::Login(QWidget *parent) :
    QLabel(parent),
    ui(new Ui::Login)
{
    //ui
    ui->setupUi(this);

    RotORP = false;
    captchaWidget = new VerifyCodeWidget(this);
    ui->verticalLayout_2->addWidget(captchaWidget);
    nowMode = userMode;
    this->setWindowFlags(Qt::FramelessWindowHint);
    ui->loginBut->setEnabled(false);
    ui->enrollBut->setEnabled(false);
    connect(ui->lowBut,&QPushButton::clicked,this,&Login::lower);//最小化
//    this->installEventFilter(this);
    ui->picLabel->setPixmap(QPixmap(":/pic/user.png").scaled(ui->picLabel->size(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation));
    connect(ui->readCheckBox,&QCheckBox::stateChanged,[=](int state){
        if(state == Qt::Checked){
            userXY();
            ui->loginBut->setEnabled(true);
            if(nowMode==userMode)
                ui->enrollBut->setEnabled(true);

        }

        else {
            ui->loginBut->setEnabled(false);
            ui->enrollBut->setEnabled(false);
        }
    });
    //数据库
    db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost");
    db.setPort(3306);
    db.setUserName("root");
    db.setPassword("root");
    db.setDatabaseName("bms");

    if(db.open())
    {
        qDebug() << "连接成功";
    }
    else {
        qDebug() << "连接数据库失败" << db.lastError().text();
        Custom_warning::Display("连接失败", Custom_warning::YES);
    }

    QFile file(":/pic/loginPage.qss");
    if(file.open(QFile::OpenModeFlag::ReadOnly)){
        this->setStyleSheet(file.readAll());
    }

}

Login::~Login()
{
    delete ui;
    qDebug()<<"执行login析构";
    db.close();
}
// 验证验证码，忽视大小写
bool verifyCaptcha(const QString &input, const QString &generated) {
    return input.toLower() == generated.toLower();
}
//登录
void Login::on_loginBut_clicked()
{
    QString inputCaptcha = ui->captchaEdit->text();
    qDebug()<<inputCaptcha<<captchaCode;
    if (inputCaptcha!= NULL && verifyCaptcha(inputCaptcha,captchaCode))
    {
        qDebug()<<"验证码输入正确";
        RotORP = true;
    } else {
        // 可以在这里重新生成验证码
        on_rotSBut_clicked(); // 重新生成验证码
        RotORP=false;
    }
    qDebug()<<"尝试登录";
    QSqlQuery query(db);
    QString ipIn =ui->noEdit->text();
    QString nameIn = ui->nameEdit->text();
    QString passIn=ui->passEdit->text();
    if(nowMode==userMode){
        if(RotORP)
//        if(true)
        {
        if(ipIn.isEmpty()||nameIn.isEmpty()||passIn.isEmpty()){
            QMessageBox messageBox(QMessageBox::Warning,
                                       "警告", "不能为空",
                                       QMessageBox::Yes);
            messageBox.exec();
            return;
        }
        QString sql=QString("select * from login where  S_Id = '%1'; ").arg(ipIn);
        if(!query.exec(sql))
        {
              qDebug() << query.lastError().text();
        }
        if (query.next()) {
             QString id = query.value(0).toString();
             QString name = query.value(1).toString();
             QString pass = query.value(2).toString();
             QString Sname;
             qDebug()<<id<<","<<name;

                 if(name==nameIn && pass== passIn){
                     sql=QString("select S_Name from student WHERE S_Id = '%1';").arg(id);
                     if(!query.exec(sql))
                     {
                         qDebug() << query.lastError().text();
                     }
                     while (query.next()) {
                         Sname=query.value(0).toString();
                     }
                     QString okOut=QString("欢迎，%1").arg(Sname);
                     Custom_warning::Display(okOut, Custom_warning::YES);
                     book * bookPage = new book(db,id);
                     connect(bookPage,&book::destroyed,this,&this->show);
                     bookPage->show();
                     this->hide();

                 }
                 else {
                     Custom_warning::Display("登录失败,请检查密码与账号", Custom_warning::YES);
                 }

        }
        else {
            Custom_warning::Display("该用户不存在", Custom_warning::YES);
        }
        }
        else {
            Custom_warning::Display("验证码错误", Custom_warning::YES);
        }
    }
    else if(nowMode==adminMode){
        if(RotORP){
        if(ipIn.isEmpty()||passIn.isEmpty()){
            QMessageBox messageBox(QMessageBox::Warning,
                                       "警告", "不能为空",
                                       QMessageBox::Yes);
            messageBox.exec();
            return;
        }
        QString sql=QString("select A_Passwd from admin where  A_Zh = '%1';").arg(ipIn);
        if(!query.exec(sql))
        {
              qDebug() << query.lastError().text();
        }
        if (query.next()) {
             QString pass = query.value(0).toString();
             qDebug()<<pass<<","<<passIn;
             if( pass == passIn){
                Admin * adminPage = new Admin(db);
                connect(adminPage,&Admin::destroyed,this,&this->show);
                adminPage->show();
                this->hide();
             }
             else {
                 Custom_warning::Display("登录失败，账号或密码错误", Custom_warning::YES);
             }
        }
        else {
            Custom_warning::Display("该用户不存在", Custom_warning::YES);
        }
        }
        else {
            Custom_warning::Display("验证码错误", Custom_warning::YES);
        }
    }

}
//注册
void Login::on_enrollBut_clicked()
{
    qDebug()<<"尝试注册";
    QString inputCaptcha = ui->captchaEdit->text();
    qDebug()<<inputCaptcha<<captchaCode;
    if (inputCaptcha!= NULL && verifyCaptcha(inputCaptcha,captchaCode))
    {
        qDebug()<<"验证码输入正确";
        RotORP = true;
    } else {
        Custom_warning::Display("验证码错误，请重试", Custom_warning::YES);
        on_rotSBut_clicked(); // 重新生成验证码
        RotORP=false;
    }
    QString ipIn =ui->noEdit->text();
    QString nameIn = ui->nameEdit->text();
    QString passIn=ui->passEdit->text();
    if(ipIn.isEmpty()||nameIn.isEmpty()||passIn.isEmpty()){
        QMessageBox messageBox(QMessageBox::Warning,
                                   "警告", "不能为空",
                                   QMessageBox::Yes, NULL);
        messageBox.exec();
        return;
    }
    QSqlQuery query(db);
    QString sql=QString("insert into login (S_Id,S_Name,S_Passwd) VALUES('%1','%2','%3')").arg(ipIn).arg(nameIn).arg(passIn);
    if(!query.exec(sql))
    {
          qDebug() << query.lastError().text();
          QMessageBox messageBox(QMessageBox::Warning,
                                     "失败", "注册失败",
                                     QMessageBox::Yes, NULL);
          messageBox.exec();

    }
    else
    {
          QMessageBox messageBox(QMessageBox::NoIcon,
                                     "成功", "注册成功",
                                     QMessageBox::Yes, NULL);
          messageBox.exec();
    }
}


void Login::on_closeBut_clicked()
{
    QMessageBox messageBox(QMessageBox::NoIcon,
                               "退出", "你确定要退出吗?",
                               QMessageBox::Yes | QMessageBox::No, NULL);
        int result=messageBox.exec();


        switch (result)
        {
        case QMessageBox::Yes:
            qDebug()<<"Yes";
            close();
            break;
        case QMessageBox::No:
            qDebug()<<"NO";
            break;
        default:
            break;
        }
}


void Login::on_comboBox_currentTextChanged(const QString &arg1)
{
    qDebug()<<"切换至"<<arg1;
    if(arg1=="管理员"){
        ui->nameEdit->clear();
        ui->nameEdit->setReadOnly(true);
        ui->enrollBut->setEnabled(false);
        nowMode = adminMode;
    }
    else if(arg1=="用户"){
        ui->nameEdit->setReadOnly(false);
        ui->enrollBut->setEnabled(true);
        nowMode = userMode;
    }
}

void Login::userXY() {
    // 创建一个对话框来显示用户协议
    QDialog *userAgreementDialog = new QDialog(this);
    userAgreementDialog->setWindowTitle(tr("用户协议"));

    // 创建一个QTextEdit来显示文本内容
    QTextEdit *textEdit = new QTextEdit;
    textEdit->setReadOnly(true); // 设置为只读，不允许用户编辑

    // 读取文本文件并显示
    QString filePath = ":/file/userRead.txt"; //
    QFile file(filePath);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&file);
        QString content = in.readAll();
        textEdit->setPlainText(content); // 直接设置文本
        file.close();
    } else {
        QMessageBox::warning(this, tr("警告"), tr("无法打开用户协议文件。"));
    }
    // 设置对话框布局
    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(textEdit);
    userAgreementDialog->setLayout(layout);
    // 设置对话框的初始大小
    userAgreementDialog->resize(800, 600);
    // 显示对话框
    userAgreementDialog->exec();
}

void Login::on_minimizeBut_clicked() {
    this->showMinimized();
}

// 最大化窗口
void Login::on_maximizeBut_clicked() {
    if (isMaximized()) {
        this->showNormal();
    } else {
        this->showMaximized();
    }
}

// 切换最大化和还原
void Login::toggleMaximizeRestore() {
    if (isMaximized()) {
        this->showNormal();
    } else {
        this->showMaximized();
    }
}
QString Login::generateCaptcha() {
    int length = 6; // 验证码长度
    QString characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    QString captcha;
    for (int i = 0; i < length; ++i) {
        captcha += characters[QRandomGenerator::global()->bounded(0, characters.length())];
    }
    captchaCode = captcha; // 保存生成的验证码以便验证
    return captcha;
}
void Login::on_rotSBut_clicked()
{
    QString captcha = generateCaptcha();
    captchaWidget->setVerifyCode(captcha);
}
void Login::on_verifyButton_clicked() {

}
